package leetcode31_40;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

/**
 * @author shhjiang_001
 * @create 2020-06-16 15:01
 */

       /*
       判断一个 9x9 的数独是否有效。只需要根据以下规则，验证已经填入的数字是否有效即可。

        数字 1-9 在每一行只能出现一次。
        数字 1-9 在每一列只能出现一次。
        数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
                输入:
                [
                ["5","3",".",".","7",".",".",".","."],
                ["6",".",".","1","9","5",".",".","."],
                [".","9","8",".",".",".",".","6","."],
                ["8",".",".",".","6",".",".",".","3"],
                ["4",".",".","8",".","3",".",".","1"],
                ["7",".",".",".","2",".",".",".","6"],
                [".","6",".",".",".",".","2","8","."],
                [".",".",".","4","1","9",".",".","5"],
                [".",".",".",".","8",".",".","7","9"]
                ]
                输出: true
                */



public class Solution36 {
    public boolean isValidSudoku(char[][] board) {
        HashSet[] line = new HashSet[9];
        HashSet[] row = new HashSet[9];
        HashSet[][] grid = new HashSet[3][3];

        for(int i= 0; i < 9;i++){
            line[i] = new HashSet();
            row[i] = new HashSet();
        }
        for(int i= 0; i < 3;i++){
            for(int j = 0;j < 3;j++){
                grid[i][j] = new HashSet();
            }
        }
        for(int i= 0; i < 9;i++){
            for(int j = 0;j < 9;j++){
                if(board[i][j] != '.'){
                    int m = i/3;
                    int n = j/3;
                    if (!line[i].contains(board[i][j])){
                        line[i].add(board[i][j]);
                    }else {
                        return false;
                    }
                    if (!row[j].contains(board[i][j])){
                        row[j].add(board[i][j]);
                    }else {
                        return false;
                    }
                    if (!grid[m][n].contains(board[i][j])){
                        grid[m][n].add(board[i][j]);
                    }else {
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
